import { defHttp, identityHttp } from '/@/utils/http/axios';
import { LoginParams, LoginResultModel, GetUserInfoModel } from './model/userModel';

import { ErrorMessageMode } from '/#/axios';

enum Api {
  Login = '/connect/token',
  Logout = '/api/account/logout',
  GetUserInfo = '/connect/userinfo',
  GetPermCode = '/app/role-navigations/menus-action-code',
}

/**
 * @description: user login api
 */
export async function loginApi(params: LoginParams, mode: ErrorMessageMode = 'modal') {
  const temp_params = Object.assign(
    {
      client_id: 'AdminManager_App',
      client_secret: '1q2w3e*',
      scope: 'openid profile AdminManager',
      grant_type: 'password',
    },
    params,
  );
  const data = await identityHttp.post(
    {
      url: Api.Login,
      params: temp_params,
    },
    {
      errorMessageMode: mode,
      isTransformResponse: false,
    },
  );
  const loginData: LoginResultModel = {
    userId: '',
    token: data.access_token,
    role: {},
  };
  return loginData;
}

/**
 * @description: getUserInfo
 */
export async function getUserInfo() {
  const data = await identityHttp.get(
    { url: Api.GetUserInfo },
    { errorMessageMode: 'none', isTransformResponse: false },
  );
  const { given_name, preferred_username, sub, name } = data;
  const userInfo: GetUserInfoModel = {
    roles: [],
    userId: sub,
    username: name,
    realName: preferred_username,
    avatar: '',
  };
  return userInfo;
}

export function getPermCode() {
  return defHttp.get<string[]>({ url: Api.GetPermCode });
}

export function doLogout() {
  return identityHttp.get({ url: Api.Logout });
}
